package com.resume.aipeople.controller;

import com.resume.aipeople.dto.ChatRequest;
import com.resume.aipeople.dto.ChatResponse;
import com.resume.aipeople.dto.ChatSessionDTO;
import com.resume.aipeople.dto.ChatMessageDTO;
import com.resume.aipeople.entity.ChatSession;
import com.resume.aipeople.service.ChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/chat")
@RequiredArgsConstructor
@Slf4j
@CrossOrigin(origins = "*")
public class ChatController {
    
    private final ChatService chatService;
    
    /**
     * 发送聊天消息
     */
    @PostMapping("/send")
    public ResponseEntity<ChatResponse> sendMessage(@Valid @RequestBody ChatRequest request) {
        try {
            log.info("收到聊天请求: 角色ID={}, 消息长度={}", request.getCharacterId(), request.getMessage().length());
            
            ChatResponse response = chatService.chat(request);
            
            if (response.isSuccess()) {
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            log.error("处理聊天请求失败", e);
            ChatResponse errorResponse = new ChatResponse("系统错误，请稍后再试");
            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }
    
    /**
     * 获取聊天历史
     */
    @GetMapping("/history/{sessionId}")
    public ResponseEntity<List<ChatMessageDTO>> getChatHistory(@PathVariable String sessionId) {
        try {
            List<ChatMessageDTO> history = chatService.getChatHistory(sessionId);
            return ResponseEntity.ok(history);
        } catch (Exception e) {
            log.error("获取聊天历史失败: {}", sessionId, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取会话信息
     */
    @GetMapping("/session/{sessionId}")
    public ResponseEntity<ChatSessionDTO> getSessionInfo(@PathVariable String sessionId) {
        try {
            ChatSessionDTO sessionInfo = chatService.getSessionInfo(sessionId);
            if (sessionInfo != null) {
                return ResponseEntity.ok(sessionInfo);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("获取会话信息失败: {}", sessionId, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取用户的聊天会话列表
     */
    @GetMapping("/sessions/{userId}")
    public ResponseEntity<List<ChatSession>> getUserSessions(@PathVariable String userId) {
        try {
            List<ChatSession> sessions = chatService.getUserSessions(userId);
            return ResponseEntity.ok(sessions);
        } catch (Exception e) {
            log.error("获取用户会话列表失败: {}", userId, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取当前登录用户的聊天会话列表
     */
    @GetMapping("/my-sessions")
    public ResponseEntity<List<ChatSessionDTO>> getCurrentUserSessions() {
        try {
            List<ChatSessionDTO> sessions = chatService.getCurrentUserSessions();
            return ResponseEntity.ok(sessions);
        } catch (Exception e) {
            log.error("获取当前用户会话列表失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 测试AI技能
     */
    @PostMapping("/test-skill")
    public ResponseEntity<ChatResponse> testSkill(@RequestBody TestSkillRequest request) {
        try {
            ChatRequest chatRequest = new ChatRequest();
            chatRequest.setCharacterId(request.getCharacterId());
            chatRequest.setMessage(request.getMessage());
            chatRequest.setPreferredSkill(request.getSkill());
            
            ChatResponse response = chatService.chat(chatRequest);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("测试AI技能失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    // 内部类用于技能测试
    public static class TestSkillRequest {
        private Long characterId;
        private String message;
        private String skill;
        
        // getters and setters
        public Long getCharacterId() { return characterId; }
        public void setCharacterId(Long characterId) { this.characterId = characterId; }
        
        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }
        
        public String getSkill() { return skill; }
        public void setSkill(String skill) { this.skill = skill; }
    }
    
    /**
     * 获取用户与特定角色的对话历史
     */
    @GetMapping("/character/{characterId}/conversation")
    public ResponseEntity<List<ChatMessageDTO>> getCharacterConversation(@PathVariable Long characterId) {
        try {
            List<ChatMessageDTO> conversation = chatService.getCharacterConversation(characterId);
            return ResponseEntity.ok(conversation);
        } catch (Exception e) {
            log.error("获取角色对话历史失败: {}", characterId, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 开始与角色的新对话
     */
    @PostMapping("/character/{characterId}/new-conversation")
    public ResponseEntity<ChatSessionDTO> startNewConversation(@PathVariable Long characterId) {
        try {
            ChatSessionDTO newSession = chatService.startNewConversation(characterId);
            return ResponseEntity.ok(newSession);
        } catch (Exception e) {
            log.error("开始新对话失败: {}", characterId, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取用户与特定角色的所有会话
     */
    @GetMapping("/character/{characterId}/sessions")
    public ResponseEntity<List<ChatSessionDTO>> getCharacterSessions(@PathVariable Long characterId) {
        try {
            List<ChatSessionDTO> sessions = chatService.getCharacterSessions(characterId);
            return ResponseEntity.ok(sessions);
        } catch (Exception e) {
            log.error("获取角色会话列表失败: {}", characterId, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 删除聊天会话
     */
    @DeleteMapping("/sessions/{sessionId}")
    public ResponseEntity<?> deleteSession(@PathVariable String sessionId) {
        try {
            log.info("删除聊天会话: {}", sessionId);
            
            boolean success = chatService.deleteSession(sessionId);
            
            if (success) {
                return ResponseEntity.ok().body(Map.of("success", true, "message", "会话删除成功"));
            } else {
                return ResponseEntity.badRequest().body(Map.of("success", false, "message", "会话删除失败"));
            }
            
        } catch (Exception e) {
            log.error("删除聊天会话失败: {}", sessionId, e);
            return ResponseEntity.internalServerError().body(Map.of("success", false, "message", "系统错误，请稍后再试"));
        }
    }
    
    /**
     * 获取消息的语音状态
     */
    @GetMapping("/message/{messageId}/audio-status")
    public ResponseEntity<Map<String, Object>> getAudioStatus(@PathVariable Long messageId) {
        try {
            Map<String, Object> status = chatService.getAudioStatus(messageId);
            return ResponseEntity.ok(status);
        } catch (Exception e) {
            log.error("获取语音状态失败: {}", messageId, e);
            return ResponseEntity.internalServerError().body(Map.of("error", "获取语音状态失败"));
        }
    }
} 